package com.example.web.system.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.web.system.entity.SaveRoleIdsByUserIdParam;
import com.example.web.system.entity.SysRole;
import com.example.web.system.entity.SysRoleParam;
import com.example.web.system.entity.SysUserRole;
import com.example.web.system.mapper.SysRoleMapper;
import com.example.web.system.mapper.SysUserRoleMapper;
import com.example.web.system.service.ISysRoleService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author kimido
 * @since 2024-07-03
 */
@Service
public class SysRoleServiceImpl extends ServiceImpl<SysRoleMapper, SysRole> implements ISysRoleService {

    @Autowired
    SysUserRoleMapper userRoleMapper;


    @Override
    public List<SysRole> checkRoles(Integer userId) {
        List<SysRole> roleList = this.baseMapper.selectList(null);

        //查询用户拥有的角色信息id
        LambdaQueryWrapper<SysUserRole> queryWrapper =new LambdaQueryWrapper<>();
        queryWrapper.eq(SysUserRole::getUserId,userId);
        List<SysUserRole> sysUserRoles = userRoleMapper.selectList(queryWrapper);

        List<Integer> roleIds = sysUserRoles.stream().map(SysUserRole::getRoleId)
                .collect(Collectors.toList());//拿到所有的角色的id

        List<SysRole> roles = roleList.stream()
                .peek(role->{
                    if(roleIds.contains(role.getRoleId())){
                        role.setChecked(true);
                    }
                }).collect(Collectors.toList());

        return roles;

//        return res;

    }


    @Override
    public IPage<SysRole> list(SysRoleParam sysRoleParam) {
        IPage<SysRole> page =new Page<>(sysRoleParam.getCurrentPage(),sysRoleParam.getPageSize());
        LambdaQueryWrapper<SysRole> queryWrapper =new LambdaQueryWrapper<>();
        String roleName = sysRoleParam.getRoleName();
        if(StringUtils.hasText(roleName)){
            queryWrapper.like(SysRole::getRoleName,roleName);
        }
        return this.baseMapper.selectPage(page,queryWrapper);

    }
}
